// 登录页面组件

import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  TextField,
  Button,
  Typography,
  Alert,
  CircularProgress,
  IconButton,
  InputAdornment,
} from '@mui/material';
import {
  Visibility,
  VisibilityOff,
  Person,
  Lock,
} from '@mui/icons-material';
import { useAuth } from '../../hooks';
import { LoginRequest } from '../../types';
import { ROUTES } from '../../router/routes';
import styles from './Login.module.css';

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [formData, setFormData] = useState<LoginRequest>({
    account: '',
    password: '',
  });
  const [showPassword, setShowPassword] = useState(false);
  const [errors, setErrors] = useState<{[key: string]: string}>({});

  const { login, loading, error } = useAuth();

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: {[key: string]: string} = {};

    if (!formData.account.trim()) {
      newErrors.account = '请输入用户名或邮箱';
    }

    if (!formData.password) {
      newErrors.password = '请输入密码';
    } else if (formData.password.length < 3) {
      newErrors.password = '密码长度至少3位';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理输入变化
  const handleInputChange = (field: keyof LoginRequest) => (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setFormData(prev => ({
      ...prev,
      [field]: event.target.value
    }));
    
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: ''
      }));
    }
  };

  // 处理登录提交
  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    try {
      await login(formData);
      // 登录成功，跳转到首页
      console.log('登录成功');
      navigate('/home');
    } catch (err) {
      console.error('登录失败:', err);
    }
  };

  // 切换密码显示
  const handleTogglePasswordVisibility = () => {
    setShowPassword(prev => !prev);
  };

  // 跳转到注册页面
  const handleGoToRegister = () => {
    navigate(ROUTES.AUTH.REGISTER);
  };

  // 跳转到忘记密码页面
  const handleForgotPassword = () => {
    navigate(ROUTES.AUTH.FORGOT_PASSWORD);
  };

  return (
    <Box className={styles.container}>
      <Card className={styles.loginCard}>
        <div className={styles.header}>
          <Typography variant="h4" className={styles.title}>
            欢迎回来
          </Typography>
          <Typography variant="body2" className={styles.subtitle}>
            登录您的账户继续使用小红书
          </Typography>
        </div>

        <form onSubmit={handleSubmit} className={styles.form}>
          <TextField
            fullWidth
            label="用户名或邮箱"
            variant="outlined"
            value={formData.account}
            onChange={handleInputChange('account')}
            error={!!errors.account}
            helperText={errors.account}
            className={styles.inputField}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Person color="action" />
                </InputAdornment>
              ),
            }}
          />

          <TextField
            fullWidth
            label="密码"
            type={showPassword ? 'text' : 'password'}
            variant="outlined"
            value={formData.password}
            onChange={handleInputChange('password')}
            error={!!errors.password}
            helperText={errors.password}
            className={styles.inputField}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Lock color="action" />
                </InputAdornment>
              ),
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    onClick={handleTogglePasswordVisibility}
                    edge="end"
                  >
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />

          <div className={styles.loadingWrapper}>
            <Button
              type="submit"
              fullWidth
              variant="contained"
              className={styles.loginButton}
              disabled={loading}
            >
              {loading ? '登录中...' : '登录'}
            </Button>
            {loading && (
              <CircularProgress size={24} className={styles.loading} />
            )}
          </div>

          {error && (
            <Alert severity="error" className={styles.errorMessage}>
              {error}
            </Alert>
          )}
        </form>

        <div className={styles.forgotPassword}>
          <a 
            href="#" 
            onClick={handleForgotPassword}
            className={styles.forgotPasswordLink}
          >
            忘记密码？
          </a>
        </div>

        <div className={styles.divider}>
          <span className={styles.dividerText}>或者</span>
        </div>

        <div className={styles.registerSection}>
          <Typography variant="body2" className={styles.registerText}>
            还没有账户？
          </Typography>
          <Button
            variant="outlined"
            fullWidth
            onClick={handleGoToRegister}
            className={styles.registerButton}
          >
            立即注册
          </Button>
        </div>
      </Card>
    </Box>
  );
};

export default Login; 